import { createMutations } from '@/store/util'
import { getUser, setUser, setTagsView } from '@/utils/storage'
import { tagsViewMutations } from 'el-admin-layout'
import { emptyOrDefault } from '@/utils'
import { request } from '@/api/request'

//刷新时从本地存储中获取用户信息
const user = getUser()

const state = {
  //是否在退出的过程中，避免重复弹框
  prepareLogout: false,

  /*用户基本信息*/
  id: emptyOrDefault(user.id, null),
  name: emptyOrDefault(user.name),
  isAdmin: emptyOrDefault(user.isAdmin, -1),
  role: emptyOrDefault(user.role, 'editor'),
  token: emptyOrDefault(user.token),
  email: emptyOrDefault(user.email),
  tel: emptyOrDefault(user.tel),
  nowOrg: emptyOrDefault(user.nowOrg, {})
}

const mutations = createMutations(state, true)

const actions = {
  login({ commit }, userInfo) {
    const { number, password } = userInfo
    return request('index/index/login', {
      number: number.trim(),
      password
    }).then(({ data: user }) => {
      if (user.isAdmin === 1) user.role = 'admin'
      else user.role = 'editor'
      //   if (user.admin === true) user.roleName = '超级管理员'
      //   user.avatar = autoCompleteUrl(user.avatar)
      commit('$all', user)
      setUser(user)
    })
  },

  logout({ commit, state, dispatch }) {
    if (state.prepareLogout) return Promise.reject()

    commit('prepareLogout', true)

    return Promise.all([
      dispatch('removeUser'),
      //因为可能开启了页签的持久化功能，所以退出登陆时通过清空store来清空持久化数据
      tagsViewMutations.delAllTagAndCache(),
      setTagsView()
    ])
      .then(() => window.location.reload())
      .finally(() => commit('prepareLogout', false))
  },

  //刷新本地存储中保存的用户数据
  refresh({ state }) {
    setUser(state)
  },

  removeUser({ commit }) {
    commit('$all', { resources: {} })
    setUser()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
